package com.itheima.service;



import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.RoleDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import entity.PageResult;
import entity.QueryPageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Autowired
    private RoleDao roleDao;


    //查询菜单数据
    @Override
    public List<Menu> getMenuByUsername(String username) {
        List<Menu> menus = menuDao.getMenuByUsername(username);
        if (menus !=null && menus.size() > 0){
            for (Menu menu : menus) {
                //封装role信息
                Set<Role> roles = roleDao.findByUsername(username);
                menu.setRoles(roles);
                List<Menu> childrenMenuList = menuDao.findMenuByParentMenuId(menu.getId());
                menu.setChildren(childrenMenuList);
            }
        }
        return menus;
    }


    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //1.调用MyBatis分页插件方法(自动帮我们做分页)  ThreadLocal, MyBatis拦截器
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //2.调用Dao
        Page<Menu> page = menuDao.selectConditions(queryPageBean.getQueryString());
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }




    //新增菜单项

    @Override
    public void add(Menu menu) {
        menuDao.add(menu);
    }

    //菜单项编辑,表单回显
    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    //编辑菜单项
    @Override
    public void edit(Menu menu) {
        menuDao.edit(menu);
    }

    //删除菜单项
    @Override
    public void delete(Integer id) {

        //1.判断当前的检查项是否被检查组引用到了
        long count =  menuDao.findCountByCheckItemId(id);
        if(count > 0){
            //2.有引用dao, 抛出异常
            throw new RuntimeException("此检查项被引用到了,不能删除");
        }

        //3.没有引用,调用Dao 删除
        menuDao.deleteById(id);
    }
    //角色需要的菜单信息
    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }
}
